/**
 * 
 */
package com.et114.modules.products.base;

import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.UUID;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

//import com.et114.components.simpletable.DataList;
import com.et114.components.image.ImageResizerV3;
import com.et114.core.action.BaseDispatchAction;
//import com.et114.core.common.AppContext;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.utility.FileUploadUtil;
import com.et114.core.utility.NumberUtils;
import com.et114.core.utility.StringPool;
import com.et114.core.utility.ThreadSynchronizer;
import com.et114.modules.products.commons.Const;
import com.et114.modules.products.commons.Context;
//import com.et114.modules.products.commons.Context;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;

/*
 * @author guanhw
 */
public class ProImageAction extends BaseDispatchAction {
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward getProImg( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC 
		List< BizOption >  bcolorOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_Color_KEY ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bcolorOps" , bcolorOps ) ;
		
		//
		ProImageForm piform = ( ProImageForm ) form ; 
		ProImageServiceImpl pisi = ( ProImageServiceImpl ) getBean( "proImageServiceImpl" ) ;
		//
		
		ProImage vo = new ProImage( ) ; 
		PropertyUtils.copyProperties ( vo , piform ) ;
		
		Long proImgId = piform.getProimgId ( ) ; 
		Byte proType = piform.getProType ( ) ;
		Long proId = piform.getProId ( ) ; 
		Byte color = piform.getColor ( ) ; 

		if ( NumberUtils.isEmptyOrZero( proImgId ) ) {
			if ( NumberUtils.isEmptyOrZero( proType ) || NumberUtils.isEmptyOrZero( proId ) ) 
				throw new Exception( "proType or proId is NULL !" ) ;
			
			
			//取颜色列表
			ProImage vov = new ProImage( ) ; 
			vov.setProId ( proId ) ; 
			vov.setProType ( proType ) ; 
			List< ProImage > cimgs = pisi.getProImageByColor ( vov ) ; 
			if ( !NumberUtils.isEmptyOrZero( piform.getColor ( ) ) ) {
				for ( ProImage proImage : cimgs ) {
					if ( color .equals (  proImage.getColor ( ) ) ) {
						vov.setWorkflg ( proImage.getWorkflg ( ) ) ;
						break  ; 
					}
				}
			}
			vov.setShowModal ( piform.getShowModal ( ) ) ;
			request.setAttribute ( "searchvo" , vov ) ;
			request.setAttribute ( "cimgs" , cimgs ) ;  
			
			
			//取颜色图片
			List imgs = pisi.getProImageList ( vo ) ; 
			request.setAttribute ( "imgs" , imgs ) ; 
			
			
			request.setAttribute ( "vo" , vo ) ;
			return mapping.findForward ( "subproimgs" ) ; 			
		}
		
		if ( !NumberUtils.isEmptyOrZero( proImgId ) ) { //load one 
			ProImage img = pisi.getProImageById ( proImgId )  ;
			request.setAttribute ( "img" , img ) ;
			return mapping.findForward ( "proimg" ) ;
		}
		return mapping.findForward ( "glerror" ) ;
	}
	
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward toEditProImg( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC 
		List< BizOption >  bcolorOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_Color_KEY ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bcolorOps" , bcolorOps ) ;
		
		ProImageForm piform = ( ProImageForm ) form ; 

		ProImage vo = new ProImage( ) ; 
		PropertyUtils.copyProperties ( vo , piform ) ;

		request.setAttribute ( "timg" , vo ) ;
		return mapping.findForward ( "proimg" ) ; 
	}
	
	

	@ SuppressWarnings ( "unchecked" )
	public  ActionForward editProImg( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC 
		//
		ProImageForm piform = ( ProImageForm ) form ; 
		ProImageServiceImpl pisi = ( ProImageServiceImpl ) getBean( "proImageServiceImpl" ) ;
		//
		Byte mark = piform.getMark ( ) ; 
		
		ProImage vo = new ProImage( ) ; 
		PropertyUtils.copyProperties ( vo , piform ) ;
		
		
		FormFile ff = piform.getPropff ( ) ;  
		Long proImgId = piform.getProimgId ( ) ; 
		Long proId = piform.getProId ( ) ; 
		Byte proType = piform.getProType ( ) ;
		Byte color = piform.getColor ( ) ; 

		if ( NumberUtils.isEmptyOrZero( proType ) ) 
			throw new Exception( "proType is NULL !" ) ;
		
		if ( NumberUtils.isEmptyOrZero( proId ) ) 
			throw new Exception( "proId is NULL !" ) ;


		if ( !NumberUtils.isEmptyOrZero( mark )  && mark.byteValue ( ) == 2 ) {
			if ( NumberUtils.isEmptyOrZero( proImgId ) ) {
				vo.setWorkflg ( Const.COMMON_STATUS_ENA ) ; 
				if ( NumberUtils.isEmptyOrZero ( proId )
						|| NumberUtils.isEmptyOrZero ( proType )
						||NumberUtils.isEmptyOrZero ( color ) ) 
					throw new Exception( "proId is NULL OR proType is NULL OR color is NULL !" ) ; 
				
				Map< String , FormFile > fileh = piform.getMultipartRequestHandler ( ).getFileElements ( );
				for ( java.util.Iterator < String > keys = fileh.keySet ( )
						.iterator ( ) ; keys.hasNext ( ) ; ) {
					ff = fileh.get ( keys.next ( ) ) ; 
					vo.setProimgId ( null ) ;
					saveAndUpdateProImg( vo , ff , pisi , request , proType ) ;
				}
				return new ActionForward (
						"proimage.go?method=getProImg&proId=" + proId
								+ "&proType=" + proType + "&color=" + color ,
						true );
			}
			else {
				proImgId = saveAndUpdateProImg( vo , ff , pisi , request , proType ) ;
			}
			
			
		}/*
		 * if ( !NumberUtils.isEmptyOrZero( mark ) && mark.byteValue ( ) == 1 )
		 * { //update color Byte modColor = piform.getModColor ( ) ; if (
		 * NumberUtils.isEmptyOrZero( color ) && NumberUtils.isEmptyOrZero(
		 * modColor ) ) throw new Exception( "color is NULL !" ) ;
		 * 
		 * if ( color .equals ( modColor ) ) { List< ProImage > imgs =
		 * pisi.getProImageList ( vo ) ; for( ProImage pi : imgs ) { pi.setColor
		 * ( modColor ) ; pisi.updateProImage ( pi ) ; } }
		 * 
		 * 
		 * return new ActionForward ( "proimage.go?method=getProImg&proId=" +
		 * proId + "&proType=" + proType + "&color=" + modColor, true );
		 * 
		 * }
		 */
		
		//Context.indexReload ( ) ;
		return new ActionForward ( "proimage.go?method=getProImg&proimgId="
				+ proImgId + "&proType=" + proType , true );
	}
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward toDisOrderProImage( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
			List< BizOption >  bcolorOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_Color_KEY ,  false  , CONST.COUNTRY_ZH  ) ;
			request.setAttribute ( "bcolorOps" , bcolorOps ) ;
		
			//PARAM
			ProImageForm piform = ( ProImageForm ) form ; 
			Byte proType = piform.getProType() ; 
			Long proId = piform.getProId ( ) ; 
			Byte color = piform.getColor ( ) ; 
			if ( NumberUtils.isEmptyOrZero ( proId )
					|| NumberUtils.isEmptyOrZero ( proType )
					||NumberUtils.isEmptyOrZero ( color ) ) 
				throw new Exception( "proId is NULL OR proType is NULL OR color is NULL !" ) ; 
	
			ProImage vo = new ProImage( ) ; 
			PropertyUtils.copyProperties ( vo , piform ) ; 

			ProImageServiceImpl pisi = ( ProImageServiceImpl ) getBean( "proImageServiceImpl" ) ;
			List< ProImage > proImages = pisi.getProImageList ( vo ) ; 
			
			request.setAttribute ( "vo" , vo ) ; 
			request.setAttribute ( "proImages" , proImages ) ;
			return mapping.findForward ( "disOrder" ) ; 
	}
	
	
	public  ActionForward disOrderProImage( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
			//PARAM
			ProImageForm piform = ( ProImageForm ) form ; 
			Byte proType = piform.getProType() ; 
			Long proId = piform.getProId ( ) ; 
			Byte color = piform.getColor ( ) ; 
			if ( NumberUtils.isEmptyOrZero ( proId )
					|| NumberUtils.isEmptyOrZero ( proType )
					||NumberUtils.isEmptyOrZero ( color ) ) 
				throw new Exception( "proId is NULL OR proType is NULL OR color is NULL !" ) ; 
			
			
			ProImageServiceImpl pisi = ( ProImageServiceImpl ) getBean( "proImageServiceImpl" ) ;
			String orders = piform.getOrders() ; 
			if ( orders != null ) {
				StringTokenizer st = new StringTokenizer( orders , StringPool.SEMICOLON ) ;
				int count = st.countTokens ( ) ; 
				ProImage vo = new ProImage( ) ; 
				for (  int i = 0 ; i <  count ; i ++ ) {
					Long orderId = Long.valueOf ( st.nextToken() );
					vo = pisi.getProImageById (  orderId ) ; 
					vo.setDisOrder ( Long.valueOf ( i + 1 ) ) ; 
					pisi.updateProImage ( vo ) ; 
				}
			}
				
			Context.doCommpass4ProImage ( proId , proType ) ;
		return new ActionForward (
				"proimage.go?method=toDisOrderProImage&proType=" + proType
						+ "&proId=" + proId + "&color=" + color , true );
	}	

	public  ActionForward updateWorkFlgProImage ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		ProImageForm piform = ( ProImageForm ) form ; 
		Long proId = piform.getProId ( ) ; 
		Byte proType = piform.getProType ( ) ;
		Byte color = piform.getColor ( ) ; 
		Byte workflg = piform.getWorkflg ( ) ; 

		if ( NumberUtils.isEmptyOrZero ( proId ) || workflg == null 
				|| NumberUtils.isEmptyOrZero ( proType )
				||NumberUtils.isEmptyOrZero ( color ) ) 
			throw new Exception( "proId is NULL OR proType is NULL OR color is NULL !" ) ; 


		ProImageServiceImpl pisi = ( ProImageServiceImpl ) getBean( "proImageServiceImpl" ) ;
		
		if( Const.COMMON_STATUS_ENA == workflg.byteValue ( ) ) 
			workflg = Const.COMMON_STATUS_DIS ; 
		else 
			workflg = Const.COMMON_STATUS_ENA ;
		

		
		pisi.updateProImageWorkFlg ( proId , color , proType , workflg ) ; 
		//Context.indexReload ( ) ; 
		return new ActionForward ( "proimage.go?method=getProImg&proId="
				+ proId + "&proType=" + proType + "&color=" + color , true );

	}
	
	
	
	public  ActionForward removeProImage ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		ProImageForm piform = ( ProImageForm ) form ; 
		Long proId = piform.getProId ( ) ; 
		Byte proType = piform.getProType ( ) ;
		Byte color = piform.getColor ( ) ; 
		
		ProImageServiceImpl pisi = ( ProImageServiceImpl ) getBean( "proImageServiceImpl" ) ;
		
		Long[] deleteIds = piform.getDeleteId ( ) ; 
		if ( deleteIds != null ) {
			for ( Long deleteId : deleteIds ) {
				ProImage vo  = pisi.getProImageById ( deleteId ) ; 
				String p = vo.getProp ( ) ;
				FileUploadUtil.removeRealPathFile ( p , request ) ; 
				pisi.removeProImageById ( deleteId ) ;
				
				//vo.setRemoveMark ( String.valueOf ( Const.COMMON_REMOVE_MARK_Y )  ) ; 
				//pisi.updateProImage ( vo ) ;
			}
		}
		
		//Context.indexReload ( ) ; 
		return new ActionForward ( "proimage.go?method=getProImg&proId="
				+ proId + "&proType=" + proType + "&color=" + color , true );
	}
	
	private Long saveAndUpdateProImg ( ProImage proImage , FormFile formFile ,
			ProImageServiceImpl pisi , HttpServletRequest request , byte proType )
			throws Exception {
		Long proImgId = proImage.getProimgId ( );
		String uploadFn = formFile.getFileName ( );
		if ( ! StringUtils.isEmpty ( uploadFn )
				&& ! StringUtils.isBlank ( uploadFn ) ) {
			FileUploadUtil upload = new FileUploadUtil ( );
			upload.setRestrictfs ( 102400 * 5 ) ;
			ThreadSynchronizer.threadEnter ( );
			try {
				String newfile = UUID.randomUUID ( ) .toString ( ) ; 
				String fn = upload.uploadv2 ( formFile , request ,
						Const.PRO_PUB_IMG_UPLOAD_PATH + proType + "/"  , newfile );
				fn = Const.PRO_PUB_IMG_UPLOAD_PATH + proType + "/" + fn;
				proImage.setProp ( fn );
		
				//set small image
				
				String px = fn.substring ( fn.lastIndexOf ( StringPool.PERIOD ) ).toUpperCase ( ) ; 
				String ufilename = formFile.getFileName ( );
				newfile += "_small"
						+ ufilename.substring (
								ufilename.lastIndexOf ( StringPool.PERIOD ) )
								.toLowerCase ( );		
				
				
				ImageResizerV3.reduceImgRealPath (   fn ,
						 AppContext.realPath + Const.PRO_PUB_IMG_SMALL_UPLOAD_PATH +  proType + "/"  ,  newfile ,
						Const.IMAGE_SUOLIE_WIDTH , Const.IMAGE_SUOLIE_HEIGHT , px );
				
				proImage.setPropsm ( Const.PRO_PUB_IMG_SMALL_UPLOAD_PATH +  proType + "/"+ newfile ) ; 
				
			} finally {
				ThreadSynchronizer.threadExit ( );
			}
		}
		
		if ( ! NumberUtils.isEmptyOrZero ( proImgId ) ) { // update
			ProImage vo = pisi.getProImageById ( proImgId );
			String prop = vo.getProp ( );
			String props = vo.getPropsm ( ) ; 
			if ( ! StringUtils.isEmpty ( uploadFn )
					&& ! StringUtils.isBlank ( uploadFn ) ) { // 存在图片 删除
				if ( ! StringUtils.isEmpty ( prop )
						&& ! StringUtils.isBlank ( prop ) ) {
					FileUploadUtil.removeRealPathFile ( prop , request );
				}
				if ( ! StringUtils.isEmpty ( props )
						&& ! StringUtils.isBlank ( props ) ) {
					FileUploadUtil.removeRealPathFile ( props , request );
				}				
				
			} else {
				// 没有则 复制
				proImage.setProp ( prop );
				proImage.setPropsm ( props );
			}
			pisi.updateProImage ( proImage ) ;
		} else {
			if ( ! StringUtils.isEmpty ( proImage.getProp ( ) )
					&& ! StringUtils.isBlank ( proImage.getProp ( ) ) ) {
				proImgId = pisi.saveProImage ( proImage );
				proImage.setDisOrder ( proImgId ) ;  
				pisi.updateProImage ( proImage ) ;
			}
		}
		return proImgId ; 
	}	
}
